// 求根节点到叶节点数字之和
package Leetcode;

// 回溯算法
class solution_129 {
    // Definition for a binary tree node.
    class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public int result = 0;

    public int sumNumbers(TreeNode root) {
        backtrack(0, root, root.val);
        return this.result;
    }

    public void backtrack(int result, TreeNode root, int currentSum) {
        if ((root.left == null) && (root.right == null)) {
            result += currentSum;
            this.result += result;
            return;
        }
        if (root.left != null) {
            currentSum = currentSum * 10 + root.left.val;
            backtrack(result, root.left, currentSum);
            currentSum /= 10;
        }
        if (root.right != null) {
            currentSum = currentSum * 10 + root.right.val;
            backtrack(result, root.right, currentSum);
            currentSum /= 10;
        }
    }
}

// 深度优先遍历
public class Solution129 {
    // Definition for a binary tree node.
    class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public int sumNumbers(TreeNode root) {
        return dfs(root, 0);
    }

    public int dfs(TreeNode root, int currentSum) {
        if (root == null)
            return 0;

        currentSum = 10 * currentSum + root.val;
        if (root.left == null && root.right == null)
            return currentSum;
        else
            return dfs(root.left, currentSum) + dfs(root.right, currentSum);
    }
}